;( function () {
    "use strict";
   	var param_map = Result.getLocationParamObject();
    var quCode = null;
    var global_param_map;
    
	 $( function () {
		App.init();
		$("#head_login_status").empty();
		if(!App.checkLogin()){
			global_param_map = {};
			$("#head_login_status").append($("#un_login_template"));
		} else {
			global_param_map = App.getCookeData();
			$("#_user_name").html(global_param_map["nickname"]);
			if(global_param_map["user_icon"] !== undefined && global_param_map["user_icon"] != null 
					&& global_param_map["user_icon"] != ""){
					$("#_head_pic").attr("src", Interface.image.pre + global_param_map["user_icon"]);
				}
			$("#head_login_status").append($("#already_login_template"));
		}
		 
		 loadByIp();
		 //定位的
		 var cityJson = App.getCity();
		 if(cityJson){
			 $("#local_city").attr("org_code", cityJson.org_code);
			 $("#local_city").attr("org_name", cityJson.org_name);
			 $("#local_city").find("a").html(cityJson.org_name);
			 $("#local_city").removeClass("yes").addClass("yes");
		 } else {
			 $("#local_city").find("a").html("没定位到城市");
			 $("#local_city").removeClass("yes");
		 }
		 //用户正在用的cit
		 var useCityJson = App.getUseCity();
		 if(useCityJson){
			 quCode = useCityJson.org_code;
			 $("#chengshi").html(useCityJson.org_name);
		 }
		 loadAllCity();
		 if(useCityJson){
			 $(".citylist li.yes").removeClass("active");
			 var len = $(".citylist").find("li[org_code="+quCode+"]").length;
			 if(len == 1){
				 $(".citylist li.yes[org_code='"+quCode+"']").removeClass("active").addClass("active");
			 } else if (len > 1) {
				 $(".citylist li.yes[org_code='"+quCode+"']").eq(0).removeClass("active").addClass("active");
			 }
		 }
		 
		 
		 loadBranner();
		 loadIndex();
		 
	 });
	 
	 
	 
	 $("#city-modal").on("focus", "#search_city", function(){
		 var that = $(this);
		 Result.doResult( {
	    	url: Interface.zs.orgGetOrgList,
	       	type: "POST",
	       	async: false,
	       	data : {}
	   	}, function ( data) {
	   		that.autocomplete(data , {  
	   			minChars: 0,
	   	        width: 680,
	   	        autoFill: false,
	            matchContains: true,  
	            highlight : false,
	            scroll : true, // 当结果集大于默认高度时是否使用卷轴显示  
	            formatItem: function(row, i, max) {  
	                 return row.org_name;  
	            },  
	            formatMatch: function(row, i, max) {  
	                 return row.org_name;  
	            },  
	            formatResult: function(row) {
	                return row.org_name;  
	            }  
	        }).result(function(event, row, formatted) {
	        	$(".citylist li.yes").removeClass("active");
	        	quCode = row.org_code;
            	var org_name = row.org_name;
				$("#chengshi").html(org_name);
				$("#city-modal").modal("close");
				//选择完更新缓存
				var jj = {"org_code" : quCode, "org_name" : org_name};
  			  	App.setUseCity(jj);
  			  	
  			  	loadBranner();
  			  	loadIndex();
				var len = $(".citylist").find("li[org_code="+quCode+"]").length;
				 if(len == 1){
					 $(".citylist li.yes[org_code='"+quCode+"']").removeClass("active").addClass("active");
				 } else if (len > 1) {
					 $(".citylist li.yes[org_code='"+quCode+"']").eq(0).removeClass("active").addClass("active");
				 }
            });  
	   	}, function ( desc ) {
	        Result.alert( "对不起:" + desc );
	    }, function ( err ) {
	        Result.alert( "错误:" + JSON.stringify(err));
	    } );
	 });
	 
	 
	 
	 function loadAllCity(){
		var $list = $("#all_city_list"),
			$template = $("#all_city_template");
			$("#host_city").empty();
		Result.doResult( {
        	url: Interface.zs.orgGetOrgList,
           	type: "POST",
           	async: false,
           	data : {}
       	}, function ( data) {
	       	var letterMap = {
	       		"A" : [], "B" : [], "C" : [], "D" :[],  "E" : [], "F" : [], "G" : [], "H" : [],
	       		"I" : [], "J" : [], "K" : [], "L" : [], "M" : [], "N" : [], "O" : [],
	       		"P" : [], "Q" : [], "R" : [], "S" : [], "T" : [], "U" : [], "V" : [],
	       		"W" : [], "X" : [], "Y" : [], "Z" : []
	       	};
	       	if( $.isArray( data ) ) {
	    		for( var i = 0, l = data.length; i < l; i++ ) {
	    			var temp = data[i]["first_letter"].toUpperCase();
	    			letterMap[temp].push(data[i]);
	            }
	    	   for(var i in letterMap){
	    		  var letterList = letterMap[i];
	    		  if(letterList.length == 0){
	    			  continue;
	    		  }
	    		  var obj = $template.clone().removeAttr( "id" );
	    		  obj.find(".letter_fist").html(i);
	    		  obj.find(".citylist").empty();
	    		  for( var j = 0, l = letterList.length; j < l; j++ ) {
	    			  var org_name = letterList[j]['org_name'];
	    			  //填补hot
	    			  if(letterList[j]['is_hot'] == 1){
	    				  var ah = '<li class="yes '+active+'" org_code="'+letterList[j]['org_code']+'" org_name="'+org_name+'"><a >'
		    			  	+org_name+'</a></li>';
	    				  $("#host_city").append(ah);
	    			  }
	    			  
	    			  //当定位没有订到的话，默认一个已开通的城市
	    			  var active = "";
	    			  if(quCode == null || quCode == ""){
	    				  $("#chengshi").html(org_name);
		    			  quCode = letterList[j]['org_code'];
		    			  active = "active";
		    			  //设置默认的缓存
		    			  var jj = {"org_code" : quCode, "org_name" : org_name};
		    			  App.setUseCity(jj);
		    		  }
	    			  var a = '<li class="yes '+active+'" org_code="'+letterList[j]['org_code']+'" org_name="'+org_name+'"><a >'
	    			  	+org_name+'</a></li>';
	    			  obj.find(".citylist").append(a);
	    			  
		          }
	    		  $list.append(obj);
	    	   }
	        }
	       	
	        $(".citylist li.yes").off().click(function(){
		       	 $(".citylist li.yes").removeClass("active");
		       	 $(this).addClass("active");
	        });
	       	
			$("#btn-city-center").on("click",function(){
				var active =  $(".citylist li.active"),
					name = active.attr("org_name"),
					code = active.attr("org_code");
				quCode = code;
				$("#chengshi").html(name);
				$("#city-modal").modal("close");
				//选择完更新缓存
				var jj = {"org_code" : quCode, "org_name" : name};
  			  	App.setUseCity(jj);
  			  	loadBranner();
			  	loadIndex();
			});
	       	
       	}, function ( desc ) {
            Result.alert( "对不起:" + desc );
        }, function ( err ) {
            Result.alert( "错误:" + JSON.stringify(err));
        } );
	 }
	 
	 
	 function loadIndex(){
		 var $list = $("#list"),
		 	$outTemplate = $("#out_template"),
		 	$innerTemplate = $("#inner_template");
		 $list.empty();
		 Result.doResult( {
			 url:  Interface.zs.gameIndexGame,
			 data: {"orgCode" : quCode},
			 type: "POST",
		 }, function ( data ) {
			 if( $.isArray( data ) ) {
				 for( var i = 0, l = data.length; i < l; i++ ) {
					 var out = $outTemplate.clone().removeAttr( "id" );
					 Result.fillData( out, data[i], "field" );
					 out.find(".ul_game_list").empty();
					 var inlist = data[i].games;
					 for( var k = 0, ll = inlist.length; k < ll; k++ ) {
						 var innner = $innerTemplate.clone().removeAttr( "id" );
						 Result.fillData( innner, inlist[k], "field" );
						 out.find(".ul_game_list").append(innner);
					 }
					 $list.append(out);
	             }
			 }
			 
			 $("#list").find(".to_detail").off().click(function(){ 
				 var id = $(this).attr("game_id"),
				 	type = $(this).attr("type"),
				 	link = $(this).attr("link"),
				 	name = $(this).attr("game_name");
				 if(type == 1){
					 Result.forward("gameDetail.html", {"game_id" : id, "game_name" : name});
				 } else {
					 window.open(link);
				 }
			 });
			 
		 }, function ( desc ) {
	       Result.alert( "对不起:" + desc );
		 }, function ( err ) {
			 Result.alert( "错误:" + JSON.stringify(err));
		 } );
		 
	 }
	 
	 
	 function loadBranner(){
		 Result.doResult( {
			 url:  Interface.zs.adQrAdvInfos,
			 data: {"type" : 2, "orgCode" : quCode},
			 type: "POST",
		 }, function ( data ) {
			 //banner
			 var $bannerTemplate = $( "#banner_template" ),
    			 $bannerList = $("#banner_list");
			 $bannerList.empty();
			 if( $.isArray( data ) ) {
				 for( var i = 0, l = data.length; i < l; i++ ) {
					 $bannerList.append( Result.fillData( $bannerTemplate.clone().removeAttr( "id" ), data[i], "field" ) );
	             }
				 $("#slider").flexslider();
			 }
			 
		 }, function ( desc ) {
	       Result.alert( "对不起:" + desc );
		 }, function ( err ) {
			 Result.alert( "错误:" + JSON.stringify(err));
		 } );
	 }
	 
	 
	 window.replace_game_id = function ( $field, id, rowVal ) {
		 $field.attr("game_id" , id);
		 $field.attr("type", rowVal['type']);
		 $field.attr("link", rowVal['game_url']);
		 $field.attr("game_name", rowVal['name']);
	 };
	 
	 
	 window.replace_logo = function ( $field, logo, rowVal ) {
		$field.attr("src", Interface.image.pre + logo);
	 };
	 
	//banner
	window.replace_banner_imgurl = function ( $field, imgurl, rowVal ) {
	 	$field.attr("src", Interface.image.pre + imgurl);
	 	var id = rowVal["id"],
	 		is_go = rowVal["is_redirect"];
	 	$field.attr("ad_id", id);
	 	if(is_go == 1){
	 		if(rowVal["out_url"] !== null && rowVal["out_url"] != ""){
	 			$field.click(function(){
		 			window.location.href= rowVal["out_url"];
			 	});
	 		} else {
	 			$field.click(function(){
	 				Result.forward("../branner/detail.html", {"ad_id" : $(this).attr("ad_id")});
	 			});
	 		}
	 		 $field.addClass("phand");
	 	} 
	};
	
	window.replace_type_icon = function($field, icon, rowVal){
		 var logo = Interface.image.pre + rowVal['type_icon'];
		 $field.css({
			 "background" : "url("+logo+")"
		  });
	 };
		 
	
}( window ) );
